#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime, UniqueConstraint
from controls.data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

"""product_img collection has
    pid:             特产id (int)
    imgid:           图片id (int)
    num:             顺序 (int, 从0开始)下标为0的是小图标,下标为1的是含价格的图片，1以后的是其他展示图片
"""

product_img_table_dict = {}


class ProductImgTables(object):
    def make_table(self, p_cityid):
        if product_img_table_dict.has_key(p_cityid):
            return product_img_table_dict[p_cityid]

        class ProductImgItem(object):
            def __init__(self, p_cityid):
                self.cityid = p_cityid

            def to_dict(self):
                res = {}
                res['pid'] = self.pid
                res['imgid'] = self.imgid
                res['num'] = self.num
                return res

            def to_min_dict(self):
                res = {}
                res['num'] = self.num
                res['url'] = self.imgid
                return res

            def __repr__(self):
                return "%d" % (self.pid)

        metadata = MetaData()
        product_img_table = Table(
            'product_img_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('pid', Integer, nullable=False),
            Column('num', Integer, nullable=False),
            Column('imgid', Integer, nullable=False),
            UniqueConstraint('pid', 'num', name='uix_pid_num')
        )
        mapper(ProductImgItem, product_img_table)
        table = {
            'metadata': metadata,
            'table': product_img_table,
            'class': ProductImgItem
        }
        product_img_table_dict[p_cityid] = table
        return table


def create_product_img_table_if_not_exist(p_cityid):
    table = ProductImgTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


# add a img for a product
def add_product_img_item(p_cityid, p_item):
    table = ProductImgTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.pid = p_item['pid']
    item.imgid = p_item['imgid']
    item.num = p_item['num']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# update a img for a product
def update_product_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = ProductImgTables().make_table(p_cityid)
    try:
        updateField = {
            table['class'].imgid: p_item['imgid']
        }
        session = Session()
        session.query(table['class']).filter(
            table['class'].pid == p_item['pid'],
            table['class'].num == p_item['num']).update(updateField, synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# delete a img for a product
def delete_product_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = ProductImgTables().make_table(p_cityid)
    try:
        session = Session()
        session.query(table['class']).filter(
            table['class'].pid == p_item['pid'],
            table['class'].num == p_item['num']).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# batch insert
# add imgs for a product
def add_product_img_dict(p_cityid, p_dict):
    table = ProductImgTables().make_table(p_cityid)
    res = {'ok': True}
    for p_item in p_dict['imgs']:
        item = table['class'](p_cityid)
        item.pid = p_dict['pid']
        item.imgid = p_item['imgid']
        item.num = p_item['num']
        try:
            session = Session()
            session.add(item)
            session.flush()
            session.commit()
            res[p_item['num']] = True
        except Exception, e:
            res[p_item['num']] = False
            res['ok'] = False
            log.exp(e)
            session.rollback()
        finally:
            session.close()
    return res


# get all products's imgs
def get_product_img_all(p_cityid):
    try:
        session = Session()
        table = ProductImgTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by().all()  # .order_by(table['class'].pid.asc())
        if not items:
            return None
        imgid_list = []
        pid_dict = {}
        res_raw = {}
        for item in items:
            if not res_raw.has_key(item.pid):
                res_raw[item.pid] = {'imgs': []}
            res_raw[item.pid]['imgs'].append(item.to_min_dict())
            pid_dict[item.pid] = item.pid
            imgid_list.append(item.imgid)
        res = {
            'imgid_list': imgid_list,
            'pid_list': pid_dict.keys(),
            'res': res_raw,
        }
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


# get a products's all imgs
def get_product_img_by_pid(p_cityid, p_pid):
    try:
        session = Session()
        table = ProductImgTables().make_table(p_cityid)

        items = session.query(table['class']).filter_by(pid=p_pid).all()
        if not items:
            return None
        imgid_list = []
        res_raw = []
        for item in items:
            res_raw.append(item.to_min_dict())
            imgid_list.append(item.imgid)
        res = {
            'imgid_list': imgid_list,
            'res': res_raw,
        }
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_product_img_by_pid_num(p_cityid, p_pid, p_num):
    try:
        session = Session()
        table = ProductImgTables().make_table(p_cityid)

        item = session.query(table['class']).filter_by(pid=p_pid, num=p_num).first()
        res = item.to_dict() if item else None

        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_product_img_table_if_not_exist(1)
    '''
    test_city = 1
    test_item_dict = {
            'pid': 2,
            'imgs' : [
                {
                    'imgid': 100000024,
                    'num': 0,
                },
                {
                    'imgid': 100000025,
                    'num': 1,
                },
                {
                    'imgid': 100000026,
                    'num': 2,
                },
            ],
        }
    #add_product_img_item(test_city, test_item_0)
    #add_product_img_item(test_city, test_item_1)
    print add_product_img_dict(test_city, test_item_dict)
    print get_product_img_all(test_city)
    '''
